import { ref, isRef, onUnmounted } from "vue";


// 格式化总秒数转为 xx天xx小时xx分xx秒格式
export const formatDuration = (second: number) => {
  let duration: string = second + "秒";
  let days = Math.floor(second / 86400);
  let hours = Math.floor((second % 86400) / 3600);
  let minutes = Math.floor(((second % 86400) % 3600) / 60);
  let seconds = Math.floor(((second % 86400) % 3600) % 60);
  if (days > 0) {
    duration = days + "天" + hours + "小时" + minutes + "分" + seconds + "秒";
  } else if (hours > 0) {
    duration = hours + "小时" + minutes + "分" + seconds + "秒";
  } else if (minutes > 0) {
    duration = minutes + "分" + seconds + "秒";
  } else if (seconds > 0) {
    duration = seconds + "秒";
  }
  return duration;
};

// 表格自动滚动
export const useAutoScrollTable = () => {
  let timer: any = ref();

  const clearTimer = () => {
    timer.value && clearInterval(timer.value);
  };

  const scroll = (table: any, duration: number = 300) => {
    const _table = isRef(table) ? table.value : table;
    const _duration: number = typeof duration === "number" ? duration : 0;


    if (_table) {
      let tableDom = (_table.$refs && _table.$refs.bodyWrapper) || _table;
      let isScroll = true;
      const dom = tableDom.querySelector(".el-scrollbar__wrap") || tableDom.querySelector(".item-container") || tableDom.querySelector(".list") || tableDom.querySelector('e-t-box');

      //鼠标放上去，停止滚动；移开，继续滚动
      dom.addEventListener("mouseover", () => {
        isScroll = false;
      });
      dom.addEventListener("mouseout", () => {
        isScroll = true;
      });

      clearTimer();

      timer.value = setInterval(() => {
        if (isScroll) {
          dom.scrollTop += 1;


          if (dom.clientHeight + dom.scrollTop + 1 >= dom.scrollHeight) {

            dom.scrollTop = 0
          }
        }
      }, _duration);
    }
  };

  onUnmounted(() => {
    clearTimer;
  });

  return { scroll };
};
